<template>
  <div>
    <el-row :gutter="10" style="margin: 10px 0px ">
      <el-col :span="17">
        <div class="inline-block"> <!-- value -->
          <el-input v-model="item.item_expression"
                    placeholder="请输入公式" @focus="item_expression_bak = item.item_expression"
                    @change="checkExpression"></el-input>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="inline-block"> <!-- value -->
          <el-input v-model="item.item_type"
                    :disabled="$parent.prop.formulaExpressionItems.length == 1"
                    :placeholder="$parent.prop.formulaExpressionItems.length == 1 ? '通用公式' : '请输入类型'"
                    @change="checkType"></el-input>
        </div>
      </el-col>
      <el-col :span="2">
        <div class="inline-block"> <!-- add button or delete button -->
          <!--          <el-button v-if="idx === 0" circle icon="el-icon-plus" plain type="success" @click="addItem"></el-button>-->
          <!--          <el-button v-else circle icon="el-icon-minus" plain type="danger" @click="deleteItem"></el-button>-->
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  export default {
    props:['item', 'idx'],
    data(){
      return{
        item_expression_bak: ''
      }
    },
    methods:{
      checkExpression(){
        try{
          let expression_bak = this.item.item_expression
          // 首尾字符可能不匹配, 加空格, 最后再去除
          expression_bak = ' ' + expression_bak + ' '
          for(let cntItem of this.$parent.prop.formulaItems){
            let reg = new RegExp(`[^a-zA-Z]${cntItem.item_id}[^a-zA-Z]`)
            while(reg.test(expression_bak)){
              let strOri = expression_bak.match(reg)[0]
              // 把所有字符都默认为1, eval计算 (1/0)结果为Infinity, 不会抛异常;
              let strNew = strOri.replace(cntItem.item_id, '(1)')
              expression_bak = expression_bak.replace(strOri, strNew)
            }
          }
          // eval 计算, 如果表达式有误, 则抛异常
          eval(expression_bak.trim())
        }catch(e){
          // 校验失败, 撤销修改
          this.item.item_expression = this.item_expression_bak
          this.$message.warning("表达式有误")
        }
      },
      checkType(){
        for (let cntItem of this.$parent.prop.formulaExpressionItems){
          if(this.item != cntItem && this.item.item_type === cntItem.item_type){
            this.item.item_type = ''
            this.$message.warning('公式类型重复, 请修改')
            return
          }
        }
      },
      addItem() {
        this.$emit("add")
      },
      deleteItem() {
        this.$emit("delete", this.idx)
      }
    }
  }
</script>

<style scoped>

</style>
